package cc.magicjson.example.demo.task.optional;

import java.util.concurrent.Future;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PriorityScheduledThreadPool extends ThreadPoolExecutor {

    private SchedulingStrategy schedulingStrategy;

    public PriorityScheduledThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, new DefaultSchedulingStrategy());
    }

    public PriorityScheduledThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
                                       SchedulingStrategy schedulingStrategy) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
                new PriorityBlockingQueue<>(11, new PriorityTaskComparator(schedulingStrategy)));
        this.schedulingStrategy = schedulingStrategy;
    }


    public void setSchedulingStrategy(SchedulingStrategy schedulingStrategy) {
        this.schedulingStrategy = schedulingStrategy;
        PriorityBlockingQueue<Runnable> newQueue = new PriorityBlockingQueue<>(11, new PriorityTaskComparator(schedulingStrategy));
        for (Runnable runnable : getQueue()) {
            newQueue.offer(runnable);
        }
        getQueue().clear();
        getQueue().addAll(newQueue);
    }

    public Future<?> submit(Runnable task, long deadline, long period, int importance) {
        PriorityScheduledTask priorityTask = new PriorityScheduledTask(task, deadline, period, importance);
        return super.submit(priorityTask);
    }


}
